<!--
 * @Description: 结果列表
 * @Author: qingyang
 * @Date: 2022-01-13 18:26:32
 * @LastEditors: qingyang
 * @LastEditTime: 2023-07-21 18:07:50
-->
<template>
  <div class="data-list-container">
    <CPageTable @register="registerPage" v-model:searchForm="searchForm">
      <template #headerRightButton>
        <el-button
          v-btnPermission="'ECI_MERGE_REPORT_DOWNLOAD'"
          type="primary"
          @click="handleMergeAndDownloadReport"
          ><CIcon type="c-xian-daochu" class="g-mr4"></CIcon>合并导出报告</el-button
        >
      </template>
      <template #batchOperaBtns>
        <el-button
          v-btnPermission="'ECI_MERGE_REPORT_DOWNLOAD'"
          type="primary"
          @click="handleMergeAndDownloadReport"
          ><CIcon type="c-xian-daochu" class="g-mr4"></CIcon>合并导出报告</el-button
        >
      </template>
      <vxe-column title="组织名称/任务编号" min-width="150">
        <template #default="scope">
          <CTableColumn
            :main-text="scope.row.organizationName"
            :sub-text="scope.row.taskNo"
          ></CTableColumn>
        </template>
      </vxe-column>
      <vxe-column title="盘查周期" min-width="120">
        <template #default="scope">
          <span>{{ formatTaskInventoryYearName(scope.row.inventoryYear) }}</span>
        </template>
      </vxe-column>
      <vxe-column title="创建人/创建时间" min-width="180">
        <template #default="scope">
          <CTableColumn
            :main-text="scope.row.creator"
            :sub-text="scope.row.createTime"
          ></CTableColumn>
        </template>
      </vxe-column>
      <vxe-column title="操作" min-width="140">
        <template #default="scope">
          <CTableButtonGroup :buttons-config="getTableButtonsConfig(scope.row)" />
        </template>
      </vxe-column>
    </CPageTable>
    <DownloadDialog
      v-model:visible="downloadVisible"
      :disable-standards="disableStandards"
      :confirmFn="handleConfirm"
    />
    <chart-view id="test" :taskNo="taskNo"></chart-view>
  </div>
</template>
<script lang="ts">
export default {
  name: 'CarbonList'
};
</script>
<script lang="ts" setup>
import { reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import { useDataConfig } from './columns';
import { formatTaskInventoryYearName } from '@/utils/index';
import ChartView from '@/businessComponents/ChartView/index.vue';
import { useMessage } from '@/hooks/useMessage';
import { CPageTable, useCPageTable, CPageTableProps } from '@/components/CPageTable';
import { useKeepAliveRefresh } from '@/hooks/useKeepAliveRefresh';
import DownloadDialog from './components/DownloadDialog/index.vue';
import type { TableButtonItem } from '@/components/CTable';
import { CTableColumn, CTableButtonGroup } from '@/components/CTable';
import { useExport } from '@/hooks/useExport';
import { exportReport } from '@/apis/eci/carbonManagement/dataList';
import type { ExportReportParams } from '@/apis/eci/carbonManagement/model/dataListModel';
import type { GetTaskDataListResult } from '@/apis/eci/carbonManagement/model/dataListModel';

const { createMessage } = useMessage();
const taskNo = ref('');
const { searchForm, tableOptions, searchOptions } = useDataConfig();
const router = useRouter();
const options = reactive<CPageTableProps>({
  title: '清册及报告',
  descText: '',
  searchOptions: searchOptions,
  tableOptions,
  enableFieldsSetting: false
});
const [registerPage, { refresh, getSelection }] = useCPageTable(options);
const downloadVisible = ref(false);
const inventoryTaskNoList = ref<string[]>([]);
const disableStandards = ref<string[]>([]);

/**
 * 下载报告
 */
const handleClick = (row: GetTaskDataListResult) => {
  inventoryTaskNoList.value = [row.taskNo];
  disableStandards.value = [];
  downloadVisible.value = true;
};
/**
 * 合并导出报告
 */
const handleMergeAndDownloadReport = () => {
  const rows = getSelection();
  if (!rows?.length) {
    createMessage.warning('请至少选择一条记录！');
    return;
  }
  console.log('handleMergeAndDownloadReport', rows);
  // 打开下载弹窗
  inventoryTaskNoList.value = rows.map(item => item.taskNo);
  disableStandards.value = ['ISO', 'GB'];
  downloadVisible.value = true;
};

// 跳转详情
const routerToDetail = (row: GetTaskDataListResult) => {
  router.push(
    `/carbonManagement/carbonList/carbonDetail?taskNo=${row.taskNo}&title=${row.organizationName}`
  );
};

function getTableButtonsConfig(row: GetTaskDataListResult): TableButtonItem[] {
  return [
    {
      text: '清册',
      btnPermission: 'ECI_INVENTORY_DETAIL_VIEW',
      onClick: () => routerToDetail(row)
    },
    {
      text: '下载报告',
      btnPermission: 'ECI_REPORT_DOWNLOAD',
      onClick: () => handleClick(row)
    }
  ];
}

useKeepAliveRefresh(refresh);

const { handleExportFile } = useExport();

/**
 * 下载确认
 * @param standard 报告标准
 */
async function handleConfirm(standard: ExportReportParams['standard']) {
  try {
    if (!inventoryTaskNoList.value?.length) {
      createMessage.error('系统异常，请刷新重试！');
      return Promise.reject('系统异常，请刷新重试！');
    }
    await handleExportFile<ExportReportParams>(exportReport, {
      standard,
      inventoryTaskNoList: inventoryTaskNoList.value
    });
    console.log('success');
    return Promise.resolve(true);
  } catch (error) {
    console.log('error', error);
    return Promise.reject(error);
  }
}
</script>

<style lang="scss" scoped>
.data-list-container {
  min-height: 80%;
}
</style>
